package com.wanyang.exception;

import com.alibaba.fastjson.JSON;
import com.wanyang.util.AssUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;


/**
 * Created by Alan on 15/8/9.
 * 这是一个全局异常拦截器
 */
public class ExceptionHandler implements HandlerExceptionResolver {
    private final Logger logger = Logger.getLogger(ExceptionHandler.class);

    public static String getErrorBackUrl(String url) {
        if (url.contains("/server")) {
            return "/server/activity-list";
        } else if (url.contains("/manage")) {
            return "/manage/activity-list";
        } else if (url.contains("/wechat")) {
            return "/wechat/activity/list";
        }
        return "/wechat/activity/list";
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        logger.error("url" + httpServletRequest.getRequestURI());
        logger.error("parameterMap" + JSON.toJSONString(httpServletRequest.getParameterMap()));
        logger.error("ExceptionHandler" + AssUtils.parse(e));
        if (httpServletRequest.getRequestURI().contains(".json")) {
            HashMap map = new HashMap();
            map.put("msg", "服务器错误，请稍后再试");
            map.put("status", "0");
            map.put("data", null);
            ModelAndView mav = new ModelAndView("jsonView");
            mav.addObject(map);
            return mav;
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("errorInfo", "服务器错误，请稍后再试");
            modelAndView.addObject("url", ExceptionHandler.getErrorBackUrl(httpServletRequest.getRequestURI()));
            return modelAndView;
        }
    }
}
